<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function loadImg(src) {
      const promise = new Promise((resolve, reject) => {
        var img = document.createElement('img')
        img.onload = function () {
          resolve(img)
        }
        img.onerror = function () {
          reject()
        }
        img.src = src
      })
      return promise
    }

    var src = 'http://www.imooc.com/static/img/index/logo_new.png'

    var result = loadImg(src)
    result.then(function (img) {
      console.log(img.width)
      return img
    }, function () {
      console.log('faild')
    }).then(function (img) {
      console.log(img.height)
    })


    let wake = (time) => {  
      return new Promise((resolve, reject) => {
        if (time > 1500) {
          setTimeout(() => {
            resolve(`${time / 1000}秒后醒来`)
          }, time)
        } else {
          reject('shibai')
        }
      })
    }

    let p1 = wake(3000)
    let p2 = wake(2000)
    let p3 = wake(1000)

    Promise.all([p1, p2, p3]).then((result) => {
      console.log(result)       // [ '3秒后醒来', '2秒后醒来' ]
    }).catch((error) => {
      console.log(error)
    })

    Promise.race([p1, p2, p3]).then((result) => {
      console.log('race', result)       // [ '3秒后醒来', '2秒后醒来' ]
    }).catch((error) => {
      console.log('race', error)
    }).finally(() => {
      console.log('finally')
    });
  </script>
</body>

</html>